// pages/index/index.js
const globalData = getApp().globalData;
const key = globalData.key;
const utils = require("../../utils/util");
Page({

  data: {
    bcgImgList: [{
        src: '/images/beach-bird-birds-235787.jpg',
        topColor: '#393836'
      },
      {
        src: '/images/clouds-forest-idyllic-417102.jpg',
        topColor: '#0085e5'
      },
      {
        src: '/images/backlit-dawn-dusk-327466.jpg',
        topColor: '#2d2225'
      },
      {
        src: '/images/accomplishment-adventure-clear-sky-585825.jpg',
        topColor: '#004a89'
      },
      {
        src: '/images/fog-himalayas-landscape-38326.jpg',
        topColor: '#b8bab9'
      },
      {
        src: '/images/asphalt-blue-sky-clouds-490411.jpg',
        topColor: '#009ffe'
      },
      {
        src: '/images/aerial-climate-cold-296559.jpg',
        topColor: '#d6d1e6'
      },
      {
        src: '/images/beautiful-cold-dawn-547115.jpg',
        topColor: '#ffa5bc'
      }
    ],
    bcgImgIndex: 0,
    cityDatas: {},
    weatherIconUrl: globalData.weatherIconUrl,
    detailsDic: {
      key: ['tmp', 'fl', 'hum', 'pcpn', 'wind_dir', 'wind_deg', 'wind_sc', 'wind_spd', 'vis', 'pres', 'cloud', ''],
      val: {
        tmp: '温度(℃)',
        fl: '体感温度(℃)',
        hum: '相对湿度(%)',
        pcpn: '降水量(mm)',
        wind_dir: '风向',
        wind_deg: '风向角度(deg)',
        wind_sc: '风力(级)',
        wind_spd: '风速(mk/h)',
        vis: '能见度(km)',
        pres: '气压(mb)',
        cloud: '云量',
      },
    },
    hourlyDatas: [],
    lifestyles: {
      'comf': '舒适度指数',
      'cw': '洗车指数',
      'drsg': '穿衣指数',
      'flu': '感冒指数',
      'sport': '运动指数',
      'trav': '旅游指数',
      'uv': '紫外线指数',
      'air': '空气污染扩散条件指数',
      'ac': '空调开启指数',
      'ag': '过敏指数',
      'gl': '太阳镜指数',
      'mu': '化妆指数',
      'airc': '晾晒指数',
      'ptfc': '交通指数',
      'fsh': '钓鱼指数',
      'spi': '防晒指数',
    },
    searchText: "",
    enableSearch: true,
    showheartbeat: true,
    setting: {},
    bcgImgAreaShow: false,
    openSettingButtonShow: false,
    tipduanyu: "",
    located: true,
    // 是否已经弹出
    hasPopped: false,
    animationMain: {},
    animationOne: {},
    animationTwo: {},
    animationThree: {}
  },
  onLoad: function (options) {
    this.reloadPage();
  },
  reloadPage() {
    //设置背景图片
    this.setbcimg();
    //获取缓存数据
    this.getCityDatas();
    //获取天气数据
    this.getWeather();
    //获取提示
    this.getBroadcast();
    //
    this.initsetting();
  },
  setbcimg(index) {
    let exe = (function () {
      this.setData({
        bcgImgIndex: index
      });
      this.setNavigationBarColor(this.data.bcgImgList[index].topColor);
      wx.setStorage({
        data: index,
        key: 'bcgImgIndex',
      })
    }).bind(this);
    if (index === undefined) {
      wx.getStorage({
        key: 'bcgImgIndex',
        success: res => {
          index = res.data || 0;
          exe();
        },
        fail: res => {
          index = 0;
          exe();
        }
      })
    } else {
      exe();
    }
  },
  setNavigationBarColor(color) {
    wx.setNavigationBarColor({
      backgroundColor: color,
      frontColor: '#ffffff'
    })
  },
  getCityDatas() {
    wx.getStorage({
      key: 'cityDatas',
      success: res => {
        this.setData({
          cityDatas: res.data
        })
      }
    })
  },
  init(params, callback) {
    this.gunding();
    wx.getLocation({
      success: res => {
        this.getWeather(`${res.longitude},${res.latitude}`);
        this.getHourly(`${res.longitude},${res.latitude}`);
        callback && callback();
      },
      fail: res => {
        console.log(res)
      }
    });
  },
  getWeather(location) {
    let reqWeather = () => wx.request({
      url: globalData.requestUrl.weather,
      data: {
        location,
        key
      },
      success: res => {
        if (res.statusCode == 200) {
          let data = res.data.HeWeather6[0];
          if (data.status == "ok") {
            this.success(data, location);
          } else {
            wx.showModal({
              title: '提示',
              content: '温度查询失败' + "未知的地点",
              complete: res => this.clearText()
            });
          }
        }
      },
      fail: res => {
        wx.showToast({
          title: '温度查询失败',
          icon: null,
          complete: res => this.clearText()
        })
      }
    });
    if (!location) {
      wx.getLocation({
        success: res => {
          location = `${res.longitude},${res.latitude}`;
          reqWeather();
        },
        fail: res => {
          this.fail();
        }
      });
    } else {
      reqWeather();
    }
  },
  success(data, location) {
    this.setData({
      openSettingButtonShow: false
    })
    wx.stopPullDownRefresh();
    let now = new Date()
    data.updateTime = now.getTime()
    data.updateTimeFormat = utils.formatDate(now, "MM-dd hh:mm");
    [1, 2, 3].forEach(r => data.daily_forecast.push(data.daily_forecast[0]));
    this.setData({
      cityDatas: data
    });
    wx.setStorage({
      data: data,
      key: 'cityDatas'
    });
  },
  fail(res) {
    wx.stopPullDownRefresh()
    let errMsg = res.errMsg || ''
    if (errMsg.indexOf('getLocation:fail')) {
      wx.showToast({
        title: '需要开启地理位置权限',
        icon: 'none',
        duration: 2500,
        success: res => {
          if (this.canUseOpenSettingApi()) {
            wx.openSetting({});
          } else {
            this.setData({
              openSettingButtonShow: true
            });
          }
        }
      })
    } else {
      wx.showToast({
        title: '网络不给力，请稍后再试',
        icon: 'none',
      })
    }
  },
  getHourly(location) {
    wx.request({
      url: `${globalData.requestUrl.hourly}`,
      data: {
        location,
        key,
      },
      success: (res) => {
        if (res.statusCode === 200) {
          let data = res.data.HeWeather6[0]
          if (data.status === 'ok') {
            this.setData({
              hourlyDatas: data.hourly || []
            })
          }
        }
      },
      fail: (res) => {
        wx.showToast({
          title: '查询失败',
          icon: 'none',
        })
      },
    })
  },
  commitSearch(res) {
    let location = res.detail.value;
    this.search(location);
  },
  clearText() {
    this.setData({
      searchText: ""
    });
  },
  gunding() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300,
    })
  },
  chooseBcg(e) {
    let dataset = ((e.currentTarget || {}).dataset) || {};
    let index = dataset.index || 0;
    if (this.data.bcgImgIndex != index) {
      this.setbcimg(index);
    }
  },
  showBcgImgArea() {
    this.setData({
      bcgImgAreaShow: true
    });
  },
  toCitychoose() {
    wx.navigateTo({
      url: '/pages/citychoose/citychoose',
    })
  },
  search(val, callback) {
    if (val === '520' || val === '521') {
      this.clearText();
      this.dance();
      return
    }
    this.setData({
      located: !val
    });
    this.gunding();
    let location = val;
    this.getWeather(location);
    this.getHourly(location);
    callback && callback();
  },
  menuMain() {
    if (!this.data.hasPopped) {
      this.popp()
      this.setData({
        hasPopped: true,
      })
    } else {
      this.takeback()
      this.setData({
        hasPopped: false,
      })
    }
  },
  menuToCitychoose() {
    this.menuMain()
    wx.navigateTo({
      url: '/pages/citychoose/citychoose',
    })
  },
  menuToSetting() {
    this.menuMain()
    wx.navigateTo({
      url: '/pages/setting/setting',
    })
  },
  menuToAbout() {
    this.menuMain()
    wx.navigateTo({
      url: '/pages/about/about',
    })
  },
  popp() {
    let animationMain = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    let animationOne = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    let animationTwo = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    let animationThree = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    let animationFour = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    animationMain.rotateZ(180).step()
    animationOne.translate(0, -60).rotateZ(360).opacity(1).step()
    animationTwo.translate(-Math.sqrt(3600 - 400), -30).rotateZ(360).opacity(1).step()
    animationThree.translate(-Math.sqrt(3600 - 400), 30).rotateZ(360).opacity(1).step()
    animationFour.translate(0, 60).rotateZ(360).opacity(1).step()
    this.setData({
      animationMain: animationMain.export(),
      animationOne: animationOne.export(),
      animationTwo: animationTwo.export(),
      animationThree: animationThree.export(),
      animationFour: animationFour.export(),
    })
  },
  takeback() {
    let animationMain = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    let animationOne = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    let animationTwo = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    let animationThree = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    let animationFour = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    animationMain.rotateZ(0).step();
    animationOne.translate(0, 0).rotateZ(0).opacity(0).step()
    animationTwo.translate(0, 0).rotateZ(0).opacity(0).step()
    animationThree.translate(0, 0).rotateZ(0).opacity(0).step()
    animationFour.translate(0, 0).rotateZ(0).opacity(0).step()
    this.setData({
      animationMain: animationMain.export(),
      animationOne: animationOne.export(),
      animationTwo: animationTwo.export(),
      animationThree: animationThree.export(),
      animationFour: animationFour.export(),
    })
  },
  hideBcgImgArea() {
    this.setData({
      bcgImgAreaShow: false
    });
  },
  canUseOpenSettingApi() {
    let systeminfo = globalData.systeminfo;
    let SDKVersion = systeminfo.SDKVersion;
    return !utils.cmpVersion(SDKVersion, '2.0.7');
  },
  onPullDownRefresh(res) {
    this.reloadPage();
  },
  getBroadcast() {
    let now = new Date().getHours();
    let tip = "";
    if (now < 12)
      tip = "上午好,今天又是美好的一天";
    else
      tip = "下午好,长时间敲代码,休息下吧";
    this.setData({
      tipduanyu: tip
    });
  },
  initsetting() {
    wx.getStorage({
      key: 'setting',
      success: res => {
        this.setData({
          setting: res.data
        });
       // this.checkUpdate(res.data);
      }
    })
  },
  checkUpdate(setting) {
    // 兼容低版本
    if (!setting.forceUpdate || !wx.getUpdateManager) {
      return
    }
    let updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate((res) => {
      console.error(res)
    })
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已下载完成，是否重启应用？',
        success: function (res) {
          if (res.confirm) {
            updateManager.applyUpdate()
          }
        }
      })
    })
  },
  dance() {
    this.setData({
      enableSearch: false,
    })
    let heartbeat = this.selectComponent('#heartbeat')
    heartbeat.dance(() => {
      this.setData({
        showHeartbeat: false,
        enableSearch: true,
      })
      this.setData({
        showHeartbeat: true,
      })
    })
  }
})